#!/usr/bin/env bash
set -euo pipefail

# 进入脚本所在目录（deploy）
cd "$(dirname "$0")"

PROJECT_NAME=${PROJECT_NAME:-my-dcyx-proj}
COMPOSE_FILE=${COMPOSE_FILE:-docker-compose.yml}

echo "[0/3] 环境检查 ..."
command -v docker >/dev/null 2>&1 || { echo "错误: 未找到 docker 命令" >&2; exit 1; }
docker compose version >/dev/null 2>&1 || { echo "错误: 未找到 docker compose 插件" >&2; exit 1; }
test -f "$COMPOSE_FILE" || { echo "错误: 未找到 compose 文件: $COMPOSE_FILE" >&2; exit 1; }

echo "[1/3] 校验镜像包校验和 ..."
if [ -f "images/SHA256SUMS" ]; then
  (cd images && sha256sum -c SHA256SUMS)
else
  echo "警告: 未找到 images/SHA256SUMS，跳过校验。" >&2
fi

echo "[2/3] 导入镜像 ..."
shopt -s nullglob
TARS=(images/*.tar)
if [ ${#TARS[@]} -eq 0 ]; then
  echo "错误: 未在 images/ 目录发现 .tar 镜像包，请先执行 package_images.sh 并上传。" >&2
  exit 1
fi
for f in "${TARS[@]}"; do
  echo "加载镜像: $f"
  docker load -i "$f"
done
shopt -u nullglob

echo "[3/3] 校验 compose 配置 ..."
docker compose -f "$COMPOSE_FILE" config -q

echo "启动服务 (project=$PROJECT_NAME) ..."
docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" up -d --remove-orphans
docker compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps

echo "完成。请确保宿主 Nginx 已将 /prod-api 和 /ws 反代到 http://127.0.0.1:8989 ，并分别将前端静态文件部署到 /var/www/admin (3000) 与 /var/www/app (3001)。"
